<template>
    <div id="app">
        <el-container>
            <el-header>
                <h1>Gitee Organization Repositories and Issues</h1>
            </el-header>
            <el-main>
                <!-- 输入组织名 -->
                <el-input
                    v-model="orgName"
                    placeholder="Enter organization name"
                    style="max-width: 400px; margin-bottom: 20px;"
                />

                <!-- 输入多个仓库名（逗号分隔） -->
                <el-input
                    v-model="repoNames"
                    placeholder="Enter repository names (comma-separated, optional)"
                    style="max-width: 400px; margin-bottom: 20px;"
                />

                <el-button type="primary" @click="fetchReposAndIssues">Fetch Repos and Issues</el-button>
                <el-button type="success" @click="exportToExcel" :disabled="organizations.length === 0">Export to Excel</el-button>

                <!-- 加载中状态 -->
                <div v-loading="loading"></div>

                <!-- 实时展示匹配到的仓库和 issue 数量 -->
                <div v-if="organizations.length > 0 || errorMessages.length > 0" style="margin-top: 20px;">
                    <p>Total Repositories: {{ totalRepos }}</p>
                    <p>Total Issues: {{ totalIssues }}</p>
                </div>

                <!-- 错误信息 -->
                <el-alert
                    v-for="(error, index) in errorMessages"
                    :key="index"
                    title="Error"
                    type="error"
                    :description="`Organization: ${error.orgName}, Repository: ${error.repoName}, Message: ${error.message}`"
                    show-icon
                    style="margin-top: 10px;"
                />
            </el-main>
        </el-container>
    </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
    data() {
        return {
            orgName: '', // 用户输入的组织名称
            repoNames: '', // 用户输入的多个仓库名称（逗号分隔，可选）
            organizations: [], // 存储组织及其仓库和 issue 信息
            loading: false, // 加载状态
            totalRepos: 0, // 总仓库数
            totalIssues: 0, // 总 issue 数
            errorMessages: [] // 用于存储错误信息
        };
    },
    methods: {
        async fetchReposAndIssues() {
            this.loading = true;
            this.organizations = [];
            this.totalRepos = 0;
            this.totalIssues = 0;
            this.errorMessages = [];

            if (this.repoNames.trim() === '') {
                // 用户未输入仓库名时，获取组织下所有仓库的 Issues
                try {
                    const repos = await this.fetchAllPages(`https://gitee.com/api/v5/orgs/${this.orgName}/repos`, {
                        access_token: '0fd1e29a051ab8f564ca7486ba5fb5cc',
                    });

                    for (const repo of repos) {
                        await this.fetchIssuesForRepo(this.orgName, repo.name);
                    }
                } catch (error) {
                    console.error(`Error fetching repositories for organization ${this.orgName}:`, error);
                }
            } else {
                // 用户输入了仓库名时，获取指定仓库的 Issues
                const repoNamesArray = this.repoNames.split(',').map(name => name.trim());
                for (const repoName of repoNamesArray) {
                    try {
                        await this.fetchIssuesForRepo(this.orgName, repoName);
                    } catch (error) {
                        console.error(`Error fetching issues for repository ${repoName}:`, error);
                    }
                }
            }

            this.loading = false;
        },

        // 获取某个仓库的所有 issues
        async fetchIssuesForRepo(orgName, repoName) {
            try {
                this.totalRepos += 1; // 更新仓库计数

                const issues = await this.fetchAllPages(`https://gitee.com/api/v5/repos/${orgName}/${repoName}/issues`, {
                    access_token: '0fd1e29a051ab8f564ca7486ba5fb5cc',
                    state:'all'
                });

                this.totalIssues += issues.length; // 更新 issue 计数

                this.organizations.push({
                    name: orgName,
                    repos: [{ name: repoName, issues }],
                });
            } catch (error) {
                if (error.response && error.response.status === 500) {
                    this.errorMessages.push({
                        orgName: orgName,
                        repoName: repoName,
                        message: error.message,
                    });
                } else {
                    console.error(`Error fetching issues for repository ${repoName}:`, error);
                }
            }
        },

        // 分页获取所有数据
        async fetchAllPages(url, params) {
            let page = 1;
            const perPage = 30;
            let allData = [];
            let hasMore = true;

            while (hasMore) {
                const response = await axios.get(url, {
                    params: {
                        ...params,
                        page,
                        per_page: perPage,
                    }
                });

                const data = response.data;
                allData = allData.concat(data);

                hasMore = data.length === perPage;
                page++;
            }

            return allData;
        },

        // 导出为 Excel 文件，所有仓库和 issue 数据放在一张表中
        exportToExcel() {
            const wb = XLSX.utils.book_new(); // 创建一个新的工作簿
            const data = []; // 用来存储所有仓库和 issue 数据

            // 添加表头
            // data.push(['Organization', 'Repository', 'Issue Title', 'Issue State']);
            data.push(['Repository', 'Issue Title', 'Issue body','Issue State', 'Issue html_url', 'created_at','finished_at', 'updated_at','（所有内容仅保留前100个字符）']);

            // 汇总所有仓库的 issue 数据
            this.organizations.forEach(org => {
                org.repos.forEach(repo => {
                    if (repo.issues && repo.issues.length > 0) {
                        repo.issues.forEach(issue => {
                            // 限制每个字段不超过 100 字符
                            const repoName = repo.name.slice(0, 100);
                            const issueTitle = issue.title.slice(0, 100);
                            const issueBody = issue.body ? issue.body.slice(0, 100) : ''; // 检查 issue.body 是否存在
                            const issueState = issue.state.slice(0, 100);
                            const issueUrl = issue.html_url.slice(0, 100);
                            const createdAt = issue.created_at.slice(0, 100);
                            const finishedAt = issue.finished_at ? issue.finished_at.slice(0, 100) : ''; // 检查 issue.finished_at 是否存在
                            const updatedAt = issue.updated_at.slice(0, 100);
                            const mark = '所有内容仅保留前100个字符';
                            data.push([repoName, issueTitle, issueBody, issueState, issueUrl, createdAt, finishedAt, updatedAt,mark]);
                        });
                    } else {
                        data.push([org.name.slice(0, 100), repo.name.slice(0, 100), 'No Issues', '']);
                    }
                });
            });


            // 创建一个单独的工作表，将所有数据放入该工作表中
            const ws = XLSX.utils.aoa_to_sheet(data);
            XLSX.utils.book_append_sheet(wb, ws, 'Gitee Issues');

            // 导出 Excel 文件
            XLSX.writeFile(wb, 'gitee_issues.xlsx');
        }
    }
};
</script>

<style scoped>
#app {
    padding: 20px;
}

.el-header h1 {
    text-align: center;
}

.el-main {
    text-align: center;
}

.el-input {
    margin-bottom: 20px;
}
</style>
